package com.xzx.bio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/9/16 22:12
 */
public class BIOSocketServer {

    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(9999));
        while (true) {
            Socket clientSocket = serverSocket.accept();
            executorService.submit(() -> {
                try {
                    handleMsg(clientSocket);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private static void handleMsg(Socket socket) throws IOException {

        byte[] bytes = new byte[5];
        int length = 0;
        // 如果超过5个字节，当前就会继续下个循环
        while ((length = socket.getInputStream().read(bytes)) != -1) {//  阻塞在这里
            String str = new String(bytes, 0, length);
            System.out.println("接收到的数据：" + str);
            socket.getOutputStream().write(str.getBytes());// 回给客户端
        }
    }
}

